/*
自动构造pages.json文件
运行：node genpages/main.js
by xiaox 2021-04-01
*/

const fs = require('fs')
const path = require('path')

// 遍历文件
function walkSync(targetPath, callback) {
	fs.readdirSync(targetPath).forEach(function(fileName) {
		var filePath = path.join(targetPath, fileName);
		var stat = fs.statSync(filePath);
		if (stat.isFile()) {
			callback(filePath);
		} else if (stat.isDirectory()) {
			walkSync(filePath, callback);
		}
	});
}

// 写入json文件
function writeFile(filename) {
	console.log(`开始写入文件：${filename}`);
	fs.writeFile(filename, content, function(err) {
		if (err) {
			return console.error(err);
		}
	});
	console.log("写入结束");
}

// 获取页面配置信息
function getPageSet(filename) {	
	var res = {};
	let data = fs.readFileSync(filename);
	let content = data.toString();	
		
	// 抓取 NAVTITLE:..., 配置项 ======================================
	let title = content.match(/NAVTITLE[^,]+/g);
	title = title ? title[0].split(":")[1].replace(/\"| /g,"") : "";	
	res["style"] = {
		"navigationBarTitleText":title
	};
	
	return res;
}

//=============================================================================
console.log(`${'='.repeat(60)}\n开始构造pages.json文件...\n${'='.repeat(60)}`)

// title带的全局样式
var globalStyle = {
	"navigationBarTextStyle": "#FFF",
	"navigationBarTitleText": "",
	"navigationBarBackgroundColor": "#f0ad4e",
	"backgroundColor": "#f0ad4e"
}

var condition = { //模式配置，仅开发期间生效
  "current": 0, //当前激活的模式（list 的索引项）
  "list": [{
      "name": "addwork", //模式名称
      "path": "pages_sub/employer/addwork/addwork", //启动页面，必选
      "query": "id=0001&name=test" //启动参数，在页面的onLoad函数里面得到。
    },
    {
      "name": "test",
      "path": "pages/component/switch/switch"
    }
  ]
}

var tabBar = {
	"color": "#7A7E83",
	"selectedColor": "#007AFF",
	"borderStyle": "black",
	"backgroundColor": "#F8F8F8",
	"list": [{
		"pagePath": "pages/index/index",
		"iconPath": "static/image/home.png",
		"selectedIconPath": "static/image/homehl.png",
		"text": "客服"
	}, {
		"pagePath": "pages/my/my",
		"iconPath": "static/image/my.png",
		"selectedIconPath": "static/image/myhl.png",
		"text": "我的"
	}]
}

var pages = [
	{
		"path": "pages/index/index",
		"style": {
			"navigationBarTitleText": "蓝华客服平台"
		}
	},
	{		
		"path": "pages/my/my",
		"style": {
			"navigationBarTitleText": "用户信息"
		}
	}
];

var res = {};
res["globalStyle"] = globalStyle;
res["condition"] = condition;
res["tabBar"] = tabBar;
res["pages"] = pages;
res["subPackages"] = [];
var subInx = -1;
// 分包pages构造
var subCatalogs = fs.readdirSync(path.resolve(__dirname, `../pages_sub`))
for (let inx in subCatalogs) {   
	catalog = subCatalogs[inx];
  console.log(catalog);
	var lpath = "";
	var pageList = [];
	let subPackages = {
		root: `pages_sub/${catalog}`,
		pages: []
	}
	res["subPackages"].push(subPackages);
	subInx++;
	pageList = res["subPackages"][subInx]["pages"];
	lpath = path.resolve(__dirname, `../pages_sub/${catalog}`); 
	walkSync(lpath, (filePath) => {   
		if (filePath.substring(filePath.length - 3).toUpperCase() != "VUE") return
   	let pagePath = filePath.split(lpath)[1].split(".")[0];	
		pagePath = pagePath.replace(/\\/g,"/").substring(1);		
		let page = {};
		page["path"] = pagePath;
		let customSets = getPageSet(filePath);
		for (let set in customSets){
			page[set] = customSets[set];			
		}		 	
		pageList.push(page)
	});
}

// console.log(JSON.stringify(res));
let content = JSON.stringify(res);
writeFile("pages.json");
